import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { TemplateRating } from '../schemas/template-rating.schema'
import { LoggerService } from '../../common/services/logger.service'

@Injectable()
export class TemplateRatingService {
    constructor(
        @InjectModel(TemplateRating.name)
        private readonly ratingModel: Model<TemplateRating>,
        private readonly logger: LoggerService
    ) { }

    // 添加评分和评论
    async addRating(data: {
        templateId: string
        userId: string
        rating: number
        comment?: string
    }): Promise<TemplateRating> {
        try {
            const rating = new this.ratingModel(data)
            await rating.save()

            this.logger.log(
                `User ${data.userId} rated template ${data.templateId} with ${data.rating} stars`,
                'TemplateRatingService'
            )

            return rating
        } catch (error) {
            if (error.code === 11000) { // 重复键错误
                throw new BadRequestException('User has already rated this template')
            }
            throw error
        }
    }

    // 更新评分和评论
    async updateRating(
        templateId: string,
        userId: string,
        data: {
            rating?: number
            comment?: string
        }
    ): Promise<TemplateRating> {
        const rating = await this.ratingModel.findOneAndUpdate(
            { templateId, userId },
            {
                ...data,
                isEdited: true,
                updatedAt: new Date()
            },
            { new: true }
        )

        if (!rating) {
            throw new NotFoundException('Rating not found')
        }

        this.logger.log(
            `User ${userId} updated rating for template ${templateId}`,
            'TemplateRatingService'
        )

        return rating
    }

    // 删除评分和评论
    async deleteRating(templateId: string, userId: string): Promise<void> {
        const result = await this.ratingModel.deleteOne({ templateId, userId })

        if (result.deletedCount === 0) {
            throw new NotFoundException('Rating not found')
        }

        this.logger.log(
            `User ${userId} deleted rating for template ${templateId}`,
            'TemplateRatingService'
        )
    }

    // 获取模板的所有评分和评论
    async getTemplateRatings(
        templateId: string,
        page = 1,
        limit = 10
    ): Promise<{
        ratings: TemplateRating[]
        total: number
        averageRating: number
    }> {
        const [ratings, total] = await Promise.all([
            this.ratingModel
                .find({ templateId })
                .sort({ createdAt: -1 })
                .skip((page - 1) * limit)
                .limit(limit)
                .exec(),
            this.ratingModel.countDocuments({ templateId })
        ])

        const averageRating = await this.getAverageRating(templateId)

        return { ratings, total, averageRating }
    }

    // 获取用户的评分
    async getUserRating(templateId: string, userId: string): Promise<TemplateRating | null> {
        return this.ratingModel.findOne({ templateId, userId }).exec()
    }

    // 获取模板的平均评分
    async getAverageRating(templateId: string): Promise<number> {
        const result = await this.ratingModel.aggregate([
            { $match: { templateId } },
            {
                $group: {
                    _id: null,
                    averageRating: { $avg: '$rating' }
                }
            }
        ])

        return result[0]?.averageRating || 0
    }

    // 获取最高评分的模板
    async getTopRatedTemplates(limit = 10): Promise<{
        templateId: string
        averageRating: number
        totalRatings: number
    }[]> {
        return this.ratingModel.aggregate([
            {
                $group: {
                    _id: '$templateId',
                    averageRating: { $avg: '$rating' },
                    totalRatings: { $sum: 1 }
                }
            },
            {
                $match: {
                    totalRatings: { $gte: 5 } // 至少5个评分
                }
            },
            {
                $sort: {
                    averageRating: -1,
                    totalRatings: -1
                }
            },
            {
                $limit: limit
            },
            {
                $project: {
                    templateId: '$_id',
                    averageRating: 1,
                    totalRatings: 1,
                    _id: 0
                }
            }
        ])
    }
} 